package com.after.saas.user.utils;

import com.after.saas.user.model.User;
import com.after.saas.common.constants.SortEnum;
import com.after.saas.common.model.query.UserQuery;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @Classname UserUtil
 * @Description TODO
 * @auth after
 * @since 2021/8/14 9:52
 */

@UtilityClass
public class UserUtil {

    public Wrapper<User> buildWrapper(UserQuery param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        Map<String, String> sortMap = param.getSortParams();
        if (!CollectionUtils.isEmpty(sortMap)) {
            for (Map.Entry<String, String> entry : sortMap.entrySet()) {
                SortEnum sortEnum = SortEnum.getEnum(entry.getValue());
                switch (sortEnum) {
                    case DESC:
                        queryWrapper.orderByDesc(entry.getKey());
                        break;
                    case ASC:
                    default:
                        queryWrapper.orderByAsc(entry.getKey());
                }
            }
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = queryWrapper.lambda();
        List<String> ignoreColumn = param.getIgnoreColumns();
        if (!CollectionUtils.isEmpty(ignoreColumn)) {
            lambdaQueryWrapper.select(User.class, i -> !ignoreColumn.contains(i.getColumn()));
        }
        lambdaQueryWrapper.eq(param.getId() != null, User::getId, param.getId());
        lambdaQueryWrapper.like(StringUtils.isNoneEmpty(param.getEmail()), User::getEmail, param.getEmail());
        lambdaQueryWrapper.like(StringUtils.isNoneEmpty(param.getMobile()), User::getMobile, param.getMobile());
        lambdaQueryWrapper.eq(StringUtils.isNoneEmpty(param.getAccount()), User::getAccount, param.getAccount());
        lambdaQueryWrapper.like(StringUtils.isNoneEmpty(param.getNickname()), User::getNickname, param.getNickname());
        lambdaQueryWrapper.like(StringUtils.isNoneEmpty(param.getUsername()), User::getUsername, param.getUsername());
        return lambdaQueryWrapper;
    }
}
